#pragma once

#include <sys/epoll.h>
#include <cstring>
#include "Log.hpp"
#include "Err.hpp"

static const int defaultfd = -1;
static const int size = 128;

class Epoller
{
public:
    Epoller()
        :_epfd(defaultfd)
    {}

    void Create()
    {
        _epfd = epoll_create(size);
        if(_epfd < 0)
        {
            logMessage(FATAL, "epoll create failed! errno: %d, err_msg: %s", errno, strerror(errno));
            exit(CREATE_EPOLL_ERR);
        }
    }

    bool AddEvent(int sockfd, const uint32_t events)
    {
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = sockfd;
        
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &ev);
        return n == 0;
    }

    ~Epoller()
    {
        if(_epfd != defaultfd)
            close(_epfd);
    }

private:
    int _epfd;
};